package com.choosefine.it.basedata.service;

import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.dao.UserInfoMapper;
import com.choosefine.it.basedata.model.UserInfo;
import com.choosefine.it.basedata.model.vo.UserInfoFindVO;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.exception.BusinessException;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.StringUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("userinfoService")
public class UserInfoService{
	@Autowired
	private UserInfoMapper userinfomapper;
	@Autowired
	private MongoTemplate mongoTemplate;
	
	public int deleteByPrimaryKey(Integer id) {
		
		return userinfomapper.deleteByPrimaryKey(id);
	}
	
	public UserInfo findByUserCode(String UserCode) {
//		mongoTemplate.save(userinfomapper.findByUserCode(UserCode));
		/*UserInfo userInfo*/
//		return userinfomapper.findByUserCode(UserCode);
		return mongoTemplate.findOne(new Query(Criteria.where("userCode").is(UserCode)), UserInfo.class);
	}

	public Integer deleteByUserCode(String UserCode) {
		int result = 0;
		String []idsStr=UserCode.split(",");
		for(int i=0;i<idsStr.length;i++){
			if (idsStr[i] != null) {
				Map<String, Object> params = new HashMap<>();
				params.put("isValid", CommonConstant.INVALID);
				params.put("usercode", idsStr[i]);
				params.put("utime", DateUtils.getNowTime());
				result+=userinfomapper.deleteByUserCode(params);
			}
		}
		return result;
	}

	public UserInfo findByPrimaryKey(Integer id) {
		return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), UserInfo.class);
	}
	
	/**
	 * 同步MongnDB中不存在的Mysql Userinfo表中的数据
	 *
	 * @Author：liaozhanggen
	 * @Create Date：2017年3月11日
	 * @param：....
	 * @return：List<UserInfo>
	 */
	public List<UserInfo> selectAll() {
		List<UserInfo> userList = userinfomapper.selectAll();
		for (UserInfo userInfo : userList) {
			if (null == this.findByUserCode(userInfo.getUserCode())) {
				mongoTemplate.save(userInfo);
			}
		}
		return userList;
	}

	public int insert(UserInfo record)throws BusinessException {
		if (record.getUserType() <=0){
			throw new BusinessException(ResultCode.FAILED,CommonConstant.PARAMETER_ERROR);
		}
		int count = userinfomapper.insert(record);
		if(count > 0){
			mongoTemplate.insert(record);
		}
		return count;
	}
	
    private Update edit(UserInfo record){
		Update update = new Update();
		if (!StringUtils.isEmpty(record.getContactAddress())) {
			update.set("contactAddress", record.getContactAddress());
		}
		if (!StringUtils.isEmpty(record.getUserName())) {
			update.set("userName", record.getUserName());
		}
		if (!StringUtils.isEmpty(record.getRealName())) {
			update.set("realName", record.getRealName());
		}
		if (!StringUtils.isEmpty(record.getNativePlace())) {
			update.set("nativePlace", record.getNativePlace());
		}
		if (record.getHeight() > 0) {
			update.set("height", record.getHeight());
		}
		if (record.getUserAge() > 0) {
			update.set("userAge", record.getUserAge());
		}
		if (record.getSex() == 0 || record.getSex() == 1) {
			update.set("sex", record.getSex());
		}
		if (!StringUtils.isEmpty(record.getEducation())) {
			update.set("education", record.getEducation());
		}
		if (!StringUtils.isEmpty(record.getRegistAddress())) {
			update.set("registAddress", record.getRegistAddress());
		}
		if (!StringUtils.isEmpty(record.getPhoneNumber())) {
			update.set("phoneNumber", record.getPhoneNumber());
		}
		if (!StringUtils.isEmpty(record.getIdcardNum())) {
			update.set("idcardNum", record.getIdcardNum());
		}
		if (!StringUtils.isEmpty(record.getIdcardZurl())) {
			update.set("idcardZurl", record.getIdcardZurl());
		}
		if (!StringUtils.isEmpty(record.getIdcardFurl())) {
			update.set("idcardFurl", record.getIdcardFurl());
		}
		if (record.getUserType() != 0) {
			update.set("userType", record.getUserType());
		}
		if (!StringUtils.isEmpty(record.getHeadIconUrl())) {
			update.set("headIconUrl", record.getHeadIconUrl());
		}
		if (record.getWorkExperience() > 0) {
			update.set("workExperience", record.getWorkExperience());
		}
		if (!StringUtils.isEmpty(record.getBirthday())) {
			update.set("birthday", record.getBirthday());
		}
		if (!StringUtils.isEmpty(record.getNational())) {
			update.set("national", record.getNational());
		}
		if (record.getCtime() != null) {
			update.set("ctime", record.getCtime());
		}
		if (record.getIsValid() == 0 || record.getIsValid() == 1) {
			update.set("isValid", record.getIsValid());
		}
		if (!StringUtils.isEmpty(record.getUserCode())) {
			update.set("userCode", record.getUserCode());
		}
		if (!StringUtils.isEmpty(record.getRegistProvinceCode())) {
			update.set("registProvinceCode", record.getRegistProvinceCode());
		}
		if (!StringUtils.isEmpty(record.getRegistProvinceName())) {
			update.set("registProvinceName", record.getRegistProvinceName());
		}
		if (!StringUtils.isEmpty(record.getRegistCityCode())) {
			update.set("registCityCode", record.getRegistCityCode());
		}
		if (!StringUtils.isEmpty(record.getRegistCityName())) {
			update.set("registCityName", record.getRegistCityName());
		}
		if (!StringUtils.isEmpty(record.getRegistCityCode())) {
			update.set("registCityCode", record.getRegistCityCode());
		}
		
		if (!StringUtils.isEmpty(record.getContactProvinceName())) {
			update.set("registProvinceName", record.getContactProvinceName());
		}
		if (!StringUtils.isEmpty(record.getContactCityCode())) {
			update.set("contactCityCode", record.getContactCityCode());
		}
		if (!StringUtils.isEmpty(record.getContactCityName())) {
			update.set("contactCityName", record.getContactCityName());
		}
		if (!StringUtils.isEmpty(record.getContactCityCode())) {
			update.set("contactCityCode", record.getContactCityCode());
		}
		
		
		if (record.getSkillsCcie() != null) {
			update.set("skillsCcie", record.getSkillsCcie());
		}
		return update;
	}

	public int update(UserInfo record) {
		int num=userinfomapper.updateByPrimaryKey(record);
		if(num>0){
            Update update=edit(record);
			mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(record.getId())),update , UserInfo.class);
		}
		return num;
	}

	public UserInfo selectUserInfoByPhoneNum(String phone){
		return userinfomapper.selectUserInfoByPhoneNum(phone);
	}
	
	public Page<UserInfoFindVO> findUserListByRole(PageDTO pageDto,Map<String, Object> params){
		PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
		return userinfomapper.findUserListByRole(params);
	}
	
	public List<UserInfo> findUsersByRealName(String realName){
		return userinfomapper.findUsersByRealName(realName);
	}
	
	/**
	 * @Description：查询分包班组承包人信息
	 * @Author：chenjian
	 * @Create Date：2017年2月23日
	 * @param：
	 * @return：
	 */
	public Page<UserInfoFindVO> findTeamUser(PageDTO pageDto,Map<String,Object> params){
		PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
		Page<UserInfoFindVO> userInfoFindVOs = userinfomapper.findUserListByRole(params);
		if(userInfoFindVOs!=null&&userInfoFindVOs.size()>0){
			for(UserInfoFindVO userInfoFindVO:userInfoFindVOs){
				params.put("userCode", userInfoFindVO.getUserCode());
				Integer id = userinfomapper.findTeamUser(params);
				if(id!=null&&id.intValue()>0){
					userInfoFindVO.setFlag(1);
				}else{
					userInfoFindVO.setFlag(0);
				}
			}
		}
		return userInfoFindVOs;
	}
    
	/**
	 * 
	 * @Description：查询工人信息
	 * @Author：chenjian
	 * @Create Date：2017年2月23日
	 * @param：
	 * @return：
	 */
	public Page<UserInfoFindVO> findTeamWorkerUser(PageDTO pageDto,Map<String,Object> params){
		PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
		Page<UserInfoFindVO> userInfoFindVOs = userinfomapper.findUserListByRole(params);
		if(userInfoFindVOs!=null&&userInfoFindVOs.size()>0){
			for(UserInfoFindVO userInfoFindVO:userInfoFindVOs){
				params.put("userCode", userInfoFindVO.getUserCode());
				Integer id = userinfomapper.findTeamWorkerUser(params);
				if(id!=null&&id.intValue()>0){
					userInfoFindVO.setFlag(1);
				}else{
					userInfoFindVO.setFlag(0);
				}
			}
		}
		return userInfoFindVOs;
	}

	/**
	 * 
	 * @Description：检查身份证号是否重复，数据大于0表示已经存在
	 * @Author：chenjian
	 * @Create Date：2017年3月10日
	 * @param：
	 * @return：
	 */
	public Integer checkCardId(Map<String, Object> params) {
		return userinfomapper.checkCardId(params);
	}

}